package com.jl.tools.stkeditor.manager;

import java.util.ArrayList;
import java.util.List;

import com.jl.tools.stkeditor.exception.DataNotMatchCodingScheamException;

/**
 * 
 * @author LuHongjun
 */
public class Manager {

	private final List<Group> groupList = new ArrayList<Group>();

	public void patch(String source) {
		// add every line to list
		List<String> list = new ArrayList<String>();
		for (String str : source.split("\n")) {
			String temp = str.trim();
			if (!temp.equals("")) {
				list.add(str.trim());
			}
		}
		int lastGroup = -1;
		int index = 1;
		for (String oneline : list) {
			LineInfo info = new LineInfo(oneline);
			if (info.isOK()) {
				if (info.getGroup() != -1 && info.getGroup() == lastGroup) {
					info.setIndex(++index);
					groupList.get(groupList.size() - 1).addData(info);
					lastGroup = info.getGroup();
				} else {// no group
					Group g = new Group();
					index = 1;
					info.setIndex(index);
					g.addData(info);
					groupList.add(g);
					lastGroup = info.getGroup();
				}
			} else {
				return;
				// continue;
			}
		}
	}

	public String[] getResult() throws DataNotMatchCodingScheamException {

		DataPosLen array = new DataPosLen();
		int index = 0;
		for (Group g : groupList) {
			g.process();
			array.add(g.getAllData(), g.getAllLength(), index++,g.getName());
		}
		return new String[]{ array.getFinalData(),array.getFinalOffsetAndLength()};
	}
}
